//
//  MessageService.m
//  express
//
//  Created by dd on 12/15/14.
//  Copyright (c) 2014 yunqi. All rights reserved.
//

#import "MessageService.h"
#import "DXKit.h"
#import "MessageDAO.h"

@implementation MessageService

+ (id)sharedInstance
{
    static MessageService *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _client = [[STOMPClient alloc] initWithHost:MQ_HOST port:MQ_PORT];
        _subscribed = NO;        
    }
    
    return self;
}

- (void)go
{
    [DX i:@"MessageCenter go"];
    
    if (_client.connected) return;
    
    DXData *data = [DXData sharedInstance];
    if (data.userId)
    {
        NSString *queue = [NSString stringWithFormat:@"/exchange/message/user.%@.*", data.userId];
        [_client connectWithHeaders:@{@"login": MQ_USERNAME, @"passcode": MQ_PASSWORD, @"host": MQ_VIRTUAL_HOST}
                  completionHandler:^(STOMPFrame *_, NSError *error) {
                      if (error)
                      {
                          NSLog(@"%@", error);
                          return;
                      }
                      
                      [DX i:@"MessageCenter connect ok"];
                      
                      [_client subscribeTo:queue
                                   headers:@{@"activemq.prefetchSize": @"1"}
                            messageHandler:^(STOMPMessage *stompMessage) {
                                NSLog(@"got message %@", stompMessage.body); // => "Hello, iOS"
                                NSDictionary *message = [DX jsonDecode:stompMessage.body];
                                if (message)
                                {
                                    [MessageService processMessage:message];
                                }
                            }];
                  }];
    }
}

- (void)stop
{
    if (_client.connected)
    {
        [_client disconnect];
    }
}

+ (void)processMessage:(NSDictionary *)message
{
    NSNumber *from_user_id = message[@"from_user_id"];
    NSNumber *to_user_id = message[@"to_user_id"];
    NSNumber *content = message[@"content"];
    NSNumber *created = message[@"created"];
    NSInteger latency = (NSInteger)[[NSDate date] timeIntervalSince1970] - created.integerValue;
    [DX i:@"%@ -> %@ (%d) : %@", from_user_id,  to_user_id, latency, content];
    
    NSDictionary *user = message[@"user"];
    if (message[@"to_user_id"])
    {
        NSNumber *toUserId = message[@"to_user_id"];
        DXData *data = [DXData sharedInstance];
        if (data.user[@"id"])
        {
            NSNumber *userId = data.user[@"id"];
            if (userId.integerValue != toUserId.integerValue)
            {

            }
        }
    }
    
    [DX i:@"message %@", message[MESSAGE_KEY_ID]];
    
    if (message[MESSAGE_KEY_ID])
    {
        NSNumber *msgId = message[MESSAGE_KEY_ID];
        if (![MessageDAO exists:msgId])
        {
            NSMutableDictionary *newMessage = [message mutableCopy];
            newMessage[MESSAGE_KEY_MESSAGE_ID] = newMessage[@"id"];
            newMessage[MESSAGE_KEY_READ] = @1;
            [MessageDAO add:newMessage];
            dispatch_async(dispatch_get_main_queue(),^{
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_MESSAGE_RECEIVED object:self userInfo:newMessage];
            });
            
            

    
        }
    }
}

@end